﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Web;
using ARS.Control.Attributes;
using ARS.Control.Custom.Entity.Fields;
using ARS.Control.Factory;

namespace ARS.Control.Custom.Entity.Forms
{
    public class SelectForm:Form
    {


        //public override void RegisterClientScriptResource(System.Web.UI.Page page,Type type)
        //{
        //    page.ClientScript.RegisterClientScriptResource(type, ResourcePath.TreeListView.js);
        //}


        private const string SYMBOL = "&nbsp;&nbsp;";
        /// <summary>
        /// 
        /// </summary>
        /// <param name="where">不懂查询</param>
        /// <param name="fieldvalue">上级的值</param>
        /// <param name="selectValue">选中项</param>
        /// <param name="field">field</param>
        /// <param name="index">开始索引</param>
        /// <param name="maxLevelNumber">最多级</param>
        /// <returns></returns>
        private StringBuilder GetOptions(string where, string fieldvalue, string selectValue, Entity.Fields.ForeignKeyField field, int index, int maxLevelNumber)
        {
            string fuhao="";
            for (int i = 0; i < index; i++)
            {
                fuhao = fuhao + SYMBOL;
            }
            if (fieldvalue != null)
            {
                field.SelectDbSelectConfig.StrWhere = where +
                                                      string.Format(" and {0}={1}", field.SelectDbSelectConfig.ParentFieldName,
                                                          fieldvalue);
            }
            StringBuilder sb_select = new StringBuilder();
            DataSet ds = Factory.DbFactory.DpProvider.GetDataList(field.SelectDbSelectConfig);

            DataTable dt = ds.Tables[0];
            foreach (DataRow dr in dt.Rows)
            {
                if (selectValue == null)
                {
                    sb_select.Append(string.Format("<option value=\"{0}\">{2}{1}</option>", dr[field.SelectDbSelectConfig.DataValueField], dr[field.SelectDbSelectConfig.DataTextField], fuhao));
                }
                else
                {
                    if (selectValue == dr[field.SelectDbSelectConfig.DataValueField].ToString())
                    {
                        sb_select.Append(string.Format("<option value=\"{0}\" selected=\"selected\">{2}{1}</option>", dr[field.SelectDbSelectConfig.DataValueField], dr[field.SelectDbSelectConfig.DataTextField], fuhao));
                    }
                    else
                    {
                        sb_select.Append(string.Format("<option value=\"{0}\">{2}{1}</option>", dr[field.SelectDbSelectConfig.DataValueField], dr[field.SelectDbSelectConfig.DataTextField], fuhao));
                    }
                }
                if (maxLevelNumber==0 || index + 1 < maxLevelNumber)
                {
                    string keyValue = dr[field.SelectDbSelectConfig.KeyField].ToString();
                    sb_select.Append(GetOptions(where, keyValue, selectValue, field, index + 1, maxLevelNumber));
                }

            }

            return sb_select;
        }

        protected override void RenderContents(System.Web.UI.HtmlTextWriter output)
        {
            Entity.Fields.ForeignKeyField field = (Entity.Fields.ForeignKeyField)base.Field;
            if (field.SelectDbSelectConfig == null)
            {
               
            }
            else
            {
               
                //默认选中的值
                string selectValue;
                if (field.RequestKeyName != null)
                {
                    selectValue = HttpContext.Current.Request.QueryString[field.RequestKeyName];
                    if (field.IsRequestKeyEncrypt && !string.IsNullOrEmpty(selectValue))
                    {
                        selectValue = PublicTool.DataHandle.Encrypt.DecryptString(selectValue);
                    }
                    else if (string.IsNullOrEmpty(selectValue))
                    {
                        selectValue = (field.Value == null ? null : field.Value.ToString());
                    }
                }
                else
                {
                    selectValue = (field.Value == null ? null : field.Value.ToString());
                }


                
                //只读
                if (field.IsReadOnly)
                {
                    if (!string.IsNullOrEmpty(selectValue))
                    {
                        string text = null;
                        DbDataReader dbDataReader = DataBase.Provider.DbFactory.DbProvider.ExecuteReader(string.Format("select {1} from {0} where {2}={3}", field.SelectDbSelectConfig.TableName, field.SelectDbSelectConfig.DataTextField, field.SelectDbSelectConfig.DataValueField, selectValue));
                        if (dbDataReader.Read())
                        {
                            text = dbDataReader[0].ToString();
                        }
                        dbDataReader.Close();
                        string html = string.Format("{1}<input id=\"{0}\" type=\"hidden\" name=\"{0}\" value='{2}'/>", field.Html_Control_Name, text, selectValue);
                        //output.Write(html);
                        output.Write(string.Format(base.GetTrHtml(), html));
                    }
                }
                else
                {
                    StringBuilder sb_select = new StringBuilder();
                    if (field.IsAllowBlank)
                    {
                        sb_select.Append(string.Format("<select id=\"{0}\" name=\"{0}\" class=\"{1}\" >", field.Html_Control_Name, field.CssName));
                    }
                    else
                    {
                        sb_select.Append(string.Format("<select id=\"{0}\" name=\"{0}\" class=\"{1}\" reg='{2}' tip='{3}' >", field.Html_Control_Name, field.CssName, field.RegexStr ?? ".+", field.Tip ?? "必须选择"));
                    }
                    if (!string.IsNullOrEmpty(field.SelectDbSelectConfig.FirstOptionText))
                    {
                        sb_select.Append(string.Format("<option value=\"{0}\">{1}</option>", field.SelectDbSelectConfig.FirstOptionValue, field.SelectDbSelectConfig.FirstOptionText));
                    }

                    if (field.SelectDbSelectConfig.StrWhere.Contains(ForeignKeyConfig.USERS) || field.SelectDbSelectConfig.StrWhere.Contains(ForeignKeyConfig.WEBSITE))
                    {
                        var user = UserFactory.CreateUser().GetUserInfo();
                        field.SelectDbSelectConfig.StrWhere = field.SelectDbSelectConfig.StrWhere.Replace(ForeignKeyConfig.USERS, user.Id.ToString())
                            .Replace(ForeignKeyConfig.WEBSITE, user.WebsiteId.ToString());
                    }
                    string where = field.SelectDbSelectConfig.StrWhere;
                    if (field.SelectDbSelectConfig.ParentFieldName != null)
                    {

                        sb_select.Append(GetOptions(where,
                            field.SelectDbSelectConfig.FieldFirstValue, selectValue, field, 0, field.SelectDbSelectConfig.MaxLevelNumber));
                    }
                    else
                    {
                        sb_select.Append(GetOptions(where,
                            field.SelectDbSelectConfig.FieldFirstValue, selectValue, field, 0, 1));

                    }
                    field.SelectDbSelectConfig.StrWhere = where;
                    sb_select.Append("</select>");
  
                    if (base.IsEntity)
                    {
                        output.Write(string.Format(base.GetTrHtml(), sb_select));
                    }
                    else
                    {
                        output.Write(sb_select.ToString());
                    }                  
                }

                
            }
            base.RenderContents(output);

        }

        public void Test()
        {
            int a = 1;
        }
    }
}
